package com.yangxiangrice.controller;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yangxiangrice.pojo.*;
import com.yangxiangrice.service.BasListService;
import com.yangxiangrice.service.GrowSeedlingsService;
import com.yangxiangrice.service.ProdPlanService;
import com.yangxiangrice.service.SeedHoldService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description: TODO
 * @author: shixiaojian
 * @date: 2021年11月23日 9:35
 */
@Controller
@RequestMapping("/growseedlings")
@CrossOrigin
@Slf4j
public class GrowSeedlingsController {

    @Autowired
    GrowSeedlingsService growSeedlingsService;

    @Autowired
    ProdPlanService prodPlanService;

    @Autowired
    BasListService basListService;

    @Autowired
    SeedHoldService seedHoldService;


    @GetMapping(value = "/getplan")
    @ResponseBody
    public Result getseed() {
        Result<List> result = new Result<>();
        Subject subject = SecurityUtils.getSubject();
        String phone = subject.getPrincipal().toString();
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("phone", phone);
        Option option = null;
        List<Option> res = new ArrayList<>();
        List<ProdPlan> list = prodPlanService.list(wrapper);
        for (ProdPlan prodPlan : list) {
            option = new Option();
            option.setLabel(prodPlan.getPlanCode());
            option.setValue(prodPlan.getPlanCode());
            res.add(option);
        }
        return result.ok(res);
    }

    @GetMapping(value = "/getbas")
    @ResponseBody
    public Result getbas() {
        Result<List> result = new Result<>();
        Subject subject = SecurityUtils.getSubject();
        String phone = subject.getPrincipal().toString();
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("phone", phone);
        Option option = null;
        List<Option> res = new ArrayList<>();
        List<BasList> list = basListService.list(wrapper);
        for (BasList basList : list) {
            option = new Option();
            option.setLabel(basList.getBasName());
            option.setValue(basList.getBasId().toString());
            res.add(option);
        }
        return result.ok(res);
    }

    @GetMapping(value = "/listpage")
    @ResponseBody
    public Result listpage(@RequestParam("page") int page,
                           @RequestParam("limit") int limit) {
        Result<IPage> result = new Result<>();
        Subject subject = SecurityUtils.getSubject();
        String phone = subject.getPrincipal().toString();
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("phone", phone);
        IPage<GrowSeedlings> growSeedlingsIPage = growSeedlingsService.seletePage(new Page<>(page, limit), wrapper);
        return result.ok(growSeedlingsIPage);
    }

    @PostMapping(value = "/save")
    @ResponseBody
    public Result save(@RequestBody GrowSeedlings growSeedlings) {
        Result<Boolean> result = new Result<>();
        growSeedlings.setCreatetime(new Timestamp(System.currentTimeMillis()));
        if (ObjectUtil.isEmpty(growSeedlings.getGrowId())) {
            Subject subject = SecurityUtils.getSubject();
            String phone = subject.getPrincipal().toString();
            growSeedlings.setPhone(phone);
            QueryWrapper wrapper = new QueryWrapper();
            wrapper.eq("planCode", growSeedlings.getSeedingCode());
            ProdPlan prodPlan = prodPlanService.getOne(wrapper);
            growSeedlings.setPlanId(prodPlan.getPlanId());
            growSeedlings.setSeedName(prodPlan.getSeedName());
            String temp = growSeedlings.getSeedingCode();
            temp += "第1批";
            growSeedlings.setSeedingCode(temp);
            Integer basId = growSeedlings.getBasId();
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("basId", basId);
            BasList bas = basListService.getOne(queryWrapper);
            if (bas.getFreePlateNu() < growSeedlings.getUsedPlateNu()) {
                return result.fail("该基地空闲秧盘数不足，请重新输出");
            }
            bas.setFreePlateNu(bas.getFreePlateNu() - growSeedlings.getUsedPlateNu());
            basListService.updateById(bas);
            boolean tag = growSeedlingsService.save(growSeedlings);
            if (tag) {
                result.ok(tag);
            } else {
                result.fail("添加失败");
            }
        } else {
            boolean tag = growSeedlingsService.updateById(growSeedlings);
            if (tag) {
                result.ok(tag);
            } else {
                result.fail("更新失败");
            }
        }
        return result;
    }

    @PostMapping(value = "/delete")
    @ResponseBody
    public Result delete(@RequestParam(value = "growId") Integer growId) {
        Result<Boolean> result = new Result<>();
        GrowSeedlings growSeedlings = growSeedlingsService.getById(growId);
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("basId", growSeedlings.getBasId());
        BasList bas = basListService.getOne(queryWrapper);
        bas.setFreePlateNu(bas.getFreePlateNu() + growSeedlings.getUsedPlateNu());
        basListService.updateById(bas);
        boolean tag = growSeedlingsService.removeById(growId);
        if (tag) {
            result.ok(tag);
        } else {
            result.fail("删除失败");
        }
        return result;
    }

    @PostMapping(value = "/deleteBatch")
    @ResponseBody
    public Result deleteBatch(@RequestBody int[] ids) {
        ArrayList<Integer> list = new ArrayList<>();
        Result<Boolean> result = new Result<>();
        for (int id : ids) {
            list.add(id);
            GrowSeedlings growSeedlings = growSeedlingsService.getById(id);
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("basId", growSeedlings.getBasId());
            BasList bas = basListService.getOne(queryWrapper);
            bas.setFreePlateNu(bas.getFreePlateNu() + growSeedlings.getUsedPlateNu());
            basListService.updateById(bas);
        }
        boolean tag = growSeedlingsService.removeByIds(list);
        if (tag) {
            result.ok(tag);
        } else {
            result.fail("删除失败");
        }
        return result;
    }

    @RequestMapping(value = "/search")
    @ResponseBody
    public Result search(@RequestParam("input") String input,
                         @RequestParam("page") int page,
                         @RequestParam("limit") int limit) {
        Result<IPage> result = new Result<>();
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.like("seedingCode", input);
        IPage<GrowSeedlings> growSeedlingsIPage = growSeedlingsService.seletePage(new Page<>(page, limit), wrapper);
        if (ObjectUtil.isEmpty(growSeedlingsIPage)) {
            result.fail("未找到符合条件的数据");
        } else {
            result.ok(growSeedlingsIPage);
        }
        return result;
    }

    @PostMapping(value = "/isenough")
    @ResponseBody
    public Result isenough(@RequestParam("basId") Integer basId,
                           @RequestParam("plateNu") Integer plateNu) {
        Result<Boolean> result = new Result();
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("basId", basId);
        BasList bas = basListService.getOne(wrapper);
        if (bas.getFreePlateNu() < plateNu) {
            result.fail("秧盘不足");
        } else {
            result.ok(true);
        }
        return result;
    }

    @GetMapping(value = "/getleftquantity")
    @ResponseBody
    public Result getleftquantity(@RequestParam(value = "seedingCode") String seedingCode) {
        Result<Integer> result = new Result<>();
        Integer used = 0;
        Integer seedNu = 0;
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("planCode", seedingCode);
        List<SeedHold> seedHolds = seedHoldService.list(wrapper);
        for (SeedHold seedHold : seedHolds) {
            seedNu+=seedHold.getSeedNu();
        }
        if (!ObjectUtil.isEmpty(seedNu)) {
            QueryWrapper wrapper_1 = new QueryWrapper();
            wrapper.eq("seedName", seedHolds.get(0).getSeedName());
            List<GrowSeedlings> list = growSeedlingsService.list(wrapper_1);
            if (!ObjectUtil.isEmpty(list)) {
                for (GrowSeedlings growSeedlings : list) {
                    used += growSeedlings.getQuantity();
                }
            }
            result.ok(seedNu - used);
        } else {
            result.fail("购种数量不足");
        }
        return result;
    }

    @PostMapping(value = "/stopgrow")
    @ResponseBody
    public Result stopgrow(@RequestParam(value = "growId") Integer growId) {
        Result<String> result = new Result<>();
        GrowSeedlings growSeedlings = growSeedlingsService.getById(growId);
        Integer basId = growSeedlings.getBasId();
        BasList basList = basListService.getById(basId);
        growSeedlings.setStatus(3);
        growSeedlingsService.updateById(growSeedlings);
        basList.setFreePlateNu(basList.getFreePlateNu() + growSeedlings.getUsedPlateNu());
        basListService.updateById(basList);
        return result.ok("该育秧计划已成功结束");
    }
}
